package com.airforce.controller;

import com.airforce.config.Redisconfig;
import com.airforce.mappers.*;
import com.airforce.model.*;
import com.airforce.utils.MD5BASE64Util;
import com.airforce.utils.ResultCode;
import com.google.common.base.Optional;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.listener.Topic;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import static com.google.common.base.Strings.emptyToNull;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping(value = "app/topic")
@RestController
public class TopicApp {

    @Autowired
    Redisconfig redisconfig;

    @Autowired
    servicesMapper servicesMapper;


    @Autowired
    wechat_userMapper wechat_userMapper;


    @Autowired
    awardMapper awardMapper;


    @Autowired
    user_topicMapper user_topicMapper;

    @Autowired
    topicMapper topicMapper;

    @Autowired
    user_awardMapper user_awardMapper;
    private final static Logger logger = LoggerFactory.getLogger(TopicApp.class);

    private final static Integer OnePhase = 5;
    private final static Integer TwoPhase = 7;
    private final static Integer ThreePhase = 10;
    private final static Integer One = 1;
    private final static Integer Two = 2;
    private final static Integer Three = 3;


    //查询所以题目
    @GetMapping(value = "list")
    public Object applist() {

        List<topic> list = topicMapper.selectByall();

        return ResultCode.SUCCESS.result(list);
    }


    //查询制定题目
    @GetMapping(value = "index")
    public Object appindex(@RequestParam Integer id) {
        topic data = topicMapper.selectByPrimaryIdx(id);
        Map map = new HashMap();
//        logger.info("当前题目下标"+id);
        String[] array = new String[]{data.getOptimea(), data.getOptimeb(), data.getOptimec(), data.getOptimed()};
        String[] AD = new String[]{"A", "B", "C", "D"};
        List list = new ArrayList();
        for (int i = 0; i < array.length; i++) {
            if (!array[i].isEmpty()) {
                Map optionMap = new HashMap();
                optionMap.put("content", array[i]);
                optionMap.put("index", AD[i]);
                list.add(optionMap);
            }
        }
        map.put("id", data.getIdx());
        map.put("content", data.getName());
        map.put("optionlist", list);

        return ResultCode.SUCCESS.result(map);
    }


    /**
     * 用户提交选项接口，
     * 功能：
     * 1.记录用户提交的题目选项
     * 2.如果是5，7，10题判断是否与中奖规则匹配
     *
     * @param token
     * @param index
     * @param content
     * @param id
     * @return
     */
    @PostMapping(value = "conmit")
    public Object optionconmit(@RequestParam String token,
                               @RequestParam String index,
                               @RequestParam String content,
                               @RequestParam @ApiParam("题目下标") Integer id

    ) {


        String[] str = MD5BASE64Util.base64decode(token).split(",");
        String openid = str[One];
        user_topic topic = new user_topic();
        topic.setOpenid(openid);
        topic.setOptioncontent(content);
        topic.setOptionindex(index);
        topic.setTopicid(id);
        pushUserTopic(topic, openid, id);
        //写入用户选项记录

//        logger.info("进行选项提交");

        return ResultCode.SUCCESS.result();

    }


    /**
     * 答题完毕触发抽奖
     *
     * @param token
     * @param id
     * @return
     */
    @GetMapping(value = "lottery")
    public Object lottery(
            @RequestParam String token,
            @RequestParam @ApiParam("题目下标") Integer id) {

        if (Optional.fromNullable(token).isPresent()) {
            String[] str = MD5BASE64Util.base64decode(token).split(",");
            String openid = str[One];
            //判断1阶段奖励
            if (id.equals(OnePhase)) {
                return pushUserAward(One, openid);

            } else if (id.equals(TwoPhase)) {
                return pushUserAward(Two, openid);
            } else if (id.equals(ThreePhase)) {
                return pushUserAward(Three, openid);
            }
        }
            return ResultCode.NO_PARM.result();



    }






    public  Object pushUserAward(Integer phase, String openid) {

        //查询某阶段的所有奖励
        List<award> awardInfo = awardMapper.selectByPhase(phase);
        List<user_topic> list = user_topicMapper.selectByOpenid(openid);
        StringBuilder userOption = new StringBuilder();
        List<Map<String,BigDecimal>>  user_award = user_awardMapper.selectByOpenid(openid);
        logger.info(openid+"开始抽奖，截止答题");
        wechat_userMapper.updataByisUser(openid);
        //获取用户选项
        if(user_award.size()==0) {
            for (user_topic item : list) {
                userOption.append(item.getOptionindex());
            }
            //判断匹配规则
            for (award item : awardInfo) {
                //获取规则组合
                String[] StrArray = item.getRule().split(",");
                for (String e : StrArray) {

                    if (e.equals(userOption.toString())) {
                        logger.info("匹配成功，分配奖品");

                        if (item.getType().equals(Two)) { //是否为高等奖励，若是则修改用户客服信息

                            logger.info("高级奖励更换信息");
                            List<services> services = servicesMapper.selectByType(Two);
                            wechat_user userinfo = wechat_userMapper.selectByopenid(openid);
                            wechat_user user = new wechat_user();
                            Integer index = 0;
                            Jedis jedis = new Jedis(redisconfig.getHost(), redisconfig.getPort());
                            if (jedis.get("services_index_2") != null) {
                                if (Integer.parseInt(jedis.get("services_index_2")) >= 0) {
                                    index = Integer.parseInt(jedis.get("services_index_2")) + 1;
                                    jedis.set("services_index_2", index.toString());
                                }
                            } else {

                                jedis.set("services_index_2", index.toString());

                            }

                            if (index > services.size() - 1) {
                                jedis.set("services_index_2", "0");
                                index = 0;
                            }

                            user.setServicesname(services.get(index).getName());
                            user.setId(userinfo.getId());
                            wechat_userMapper.updateByPrimaryKeySelective(user);

                        }
                        Map map = new HashMap();
                        user_award user = new user_award();
                        user.setAwardid(item.getId());
                        user.setOpenid(openid);
                        user.setNumber(item.getPhase());
                        map.put("money", item.getPrice());
                        logger.info("添加获奖记录");
                        user_awardMapper.insertSelective(user);
                        return ResultCode.SUCCESS.result(map);
                    }
                }
            }
        }
        logger.info("未匹配成功，谢谢参与");
        return   ResultCode.LOST_AWARD.result();

    }

    public void pushUserTopic(user_topic user_topic, String openid,Integer id) {

        if (Optional.fromNullable(user_topic).isPresent()) {
            if (id<=OnePhase&&id>0) {
                user_topic.setPhase(One);
            } else if (id>OnePhase&&id<=TwoPhase) {
                user_topic.setPhase(Two);
            } else if (id>TwoPhase&&id<=ThreePhase) {
                user_topic.setPhase(Three);
            }
            user_topicMapper.insertSelective(user_topic);
            wechat_user userinfo = wechat_userMapper.selectByopenid(openid);
            //变更用户信息
            wechat_user user = new wechat_user();
            user.setId(userinfo.getId());

//                logger.info("当前id"+id);
                user.setAnswernum(userinfo.getAnswernum() - One);


            user.setNowanswer(userinfo.getNowanswer() + One);
            wechat_userMapper.updateByPrimaryKeySelective(user);
        }

    }




    public static void main(String args[]) {
        String s = "aaa,";
        System.out.println(s.split(",")[0]);



    }


}
